#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    vector<vector<int>> fourSum(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> ret;
        for (int i = 0; i < nums.size();)
        {
            for (int j = i + 1; j < nums.size();)
            {
                int left = j + 1;
                int right = nums.size() - 1;
                long long  ae = (long long)target - nums[i] - nums[j];
                while (left < right)
                {
                    int sum = nums[left] + nums[right];
                    if (sum < ae)
                    {
                        left++;
                    }
                    else if (sum > ae)
                    {
                        right--;
                    }
                    else
                    {
                        ret.push_back({ nums[i],nums[j],nums[left++],nums[right--] });
                        while (left < right && nums[left] == nums[left - 1])
                        {
                            left++;
                        }
                        while (left < right && nums[right] == nums[right + 1])
                        {
                            right--;
                        }
                    }

                }
                j++;
                while (j < nums.size() && nums[j] == nums[j - 1])
                {
                    j++;
                }
            }
            i++;
            while (i < nums.size() && nums[i] == nums[i - 1])
            {
                i++;
            }
        }
        return ret;
    }
};
int main()
{
    Solution as;
    vector<int> aq({ 14,6,56,7,867,9,89,78,9,70,7,0,3,5,2,5 });
    vector<vector<int>> x=as.fourSum(aq, 12);
    for (auto w : x)
    {
        for (auto s : w)
        {
            cout << s << " ";
        }
        cout << endl;
    }
    return 0;
}